<template>
  <a-modal class="common-modal" :title="$t('video.selectVideo')" :footer="null" :width="560" :visible="visible" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading" size="large">
      <a-form ref="formRef" layout="vertical"  :model="formState" :rules="modalRules" class="p-20 pb-2" >
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item :label="$t('basicData.staff')+':'" name="staffId"  @change="onChange">
              <a-select  v-model:value="formState.staffId" :placeholder="$t('common.pleaseSelect')">
                <a-select-option v-for="(item, index) in staffList" :key="index" :value="item.id">{{item.nickName}}</a-select-option>
              </a-select>
            </a-form-item> 
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('video.beatName')+':' " name="type">
              <a-select  v-model:value="formState.type" :placeholder="$t('common.pleaseSelect')">
                <a-select-option :value="1">{{ $t('video.best') }}</a-select-option>
                <a-select-option :value="2">{{ $t('video.worst') }}</a-select-option>
              </a-select>
            </a-form-item> 
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('video.productionTimePeriod')+':' " name="prodTime" >
              <a-range-picker v-model:value="formState.prodTime"  value-format="YYYY-MM-DD HH:mm:ss" show-time @change="onChange"/>
            </a-form-item> 
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('video.videoTimePeriod')+':' " name="beatTime">
              <a-select v-model:value="formState.beatTime" :placeholder="$t('common.pleaseSelect')" @change="onBeatTimeChange" :disabled="!(formState.prodTime?.length && formState.staffId)">
                <a-select-option v-for="(item, index) in timeList" :key="index" :value="`${item.startTime}-${item.endTime}`">
                  {{`${formatTime(item.startTime, 'YYYY-MM-DD HH:mm:ss')}-${formatTime(item.endTime, 'YYYY-MM-DD HH:mm:ss')}`}}
                </a-select-option>
              </a-select>
            </a-form-item> 
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('video.elapsedTotalTime')+':'" name="spendTime" >
              <a-input v-model:value.trim="formState.spendTime" disabled :placeholder="$t('common.pleaseInput')" :maxLength="6" />
            </a-form-item> 
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('video.exportVideoName')+':' " name="name">
              <a-input v-model:value.trim="formState.name" :placeholder="$t('common.pleaseInput')" :maxLength="10" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="common-modal-footer1">
        <div>
          <a-button @click="handlePreview" type="primary" class="confirm">{{ $t('video.clickPreview') }}</a-button>
        </div>
        <div>
          <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
          <a-button @click="handleOk(true)" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
        </div>
      </div>
      <PreviewVideoModal ref="previewVideoModalRef"/>
    </a-spin>
  </a-modal>
</template>

<script setup name="operateEmpModal">
import moment from 'moment'
import { formatTime } from '@/utils'
import { ref, nextTick, onMounted } from 'vue' 
import axios from '@/utils/request'
import { message } from 'ant-design-vue' 
import { modalRules } from './config'
import PreviewVideoModal from './previewVideoModal.vue'
const emits = defineEmits(['ok']) 
let visible = ref(false)
let confirmLoading = ref(false)
let formState = ref({})
const formRef = ref() 
const previewVideoModalRef = ref()
let recordInfo = ref({})
let staffList = ref([])
let timeList = ref([])
let beatId = ref()
const open = async (record ) => { 
  visible.value = true 
  recordInfo.value = Object.assign({}, record)
  await getStaff()
  await nextTick()
  formState.value = recordInfo.value
  formRef.value.resetFields()
} 
const handlePreview = async () =>  {
  beatId.value = null
  await handleOk(false)
  if( beatId.value ) previewVideoModalRef.value.open(beatId.value) 
}
const getQueryParams = () => {
  let { staffId, type, beatTime, spendTime, name } = formState.value
  let { processId, roadMapId, processVersionId } = recordInfo.value
  let ary = beatTime.split('-')  
  let params = {
    staffId, type, spendTime, name,
    startTime: parseInt(ary[0]),
    endTime: parseInt(ary[1]),
    processId, 
    roadMapId,
    processVersionId,
    id: beatId.value
  }
  return params
}
const handleOk = async (isConfirm) => {
  try {
    await formRef.value.validateFields()
    let params = getQueryParams()
    confirmLoading.value = true 
    let res = await axios.postAction('/api/monitor/beat/createBeat' , params)
    confirmLoading.value = false
    if (res.success) {
      message.success(res.msg)
      if(isConfirm) { 
        emits('ok')
        handleCancel()
      } else {
        beatId.value = res.data
        confirmLoading.value = false
      }
    } else {
      confirmLoading.value = false
    }
  } catch {
    confirmLoading.value = false
    console.log('error')
  }
}
const handleCancel = () => {
  formState.value = {}
  confirmLoading.value = false
  formRef.value.resetFields()
  visible.value = false 
}
const onBeatTimeChange = () => {
  let { beatTime } = formState.value
  let ary = beatTime.split('-')  
  let sec = moment(parseInt(ary[1])).diff(moment(parseInt(ary[0])), 'seconds')

  console.log("🚀 ~ file: operateModal.vue:122 ~ onBeatTimeChange ~ sec:", sec)
  formState.value.spendTime = beatTime ? sec : '' 
   
}
const getStaff =async () => {
  confirmLoading.value = false
  try {  
    let params = {  processId: recordInfo.value.processId, roadMapId: recordInfo.value.roadMapId }
    let res = await axios.postAction('/api/monitor/beat/listStaff', params) 
    staffList.value = res.success ? res.data || [] : []
    confirmLoading.value = false
  } catch {
    staffList.value = []
    confirmLoading.value = false
  }
}
const onChange = async () => {
  formState.value.beatTime = undefined
  let {prodTime,staffId } = formState.value
  console.log("🚀 ~ file: operateModal.vue:129 ~ onChange ~ prodTime:", prodTime)
  if(prodTime?.length && staffId) { 
    try {  
      let params = { 
        processId: recordInfo.value.processId, 
        roadMapId: recordInfo.value.roadMapId,
        staffId,
        startTime: moment(prodTime[0]).valueOf() ,
        endTime: moment(prodTime[1]).valueOf() 
      }
      let res = await axios.postAction('/api/monitor/beat/listVideoTime', params) 
      timeList.value = res.success ? res.data || [] : [] 
    } catch {
      timeList.value = [] 
    }
  }  
}
onMounted(async () => {

})
defineExpose({
  open
})

</script>